<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: pl125 <xskjs888@163.com>
// +----------------------------------------------------------------------

namespace api\wxapp\controller;

use api\wxapp\controller\ApiBaseController;
use think\Db;
use api\wxapp\model\Shop;
use api\wxapp\model\Clerk;
use api\wxapp\model\User;
use api\wxapp\model\ShopGoods;
use api\wxapp\model\Balance;
use api\wxapp\model\Goods;
use api\wxapp\model\Order;
use api\wxapp\model\GoodsCate;
use api\wxapp\model\OrderList;
use api\wxapp\model\Refund;
use api\wxapp\model\GoodsActivity;
class StoreController extends ApiBaseController
{
    public function initialize()
    {
        parent::initialize();
        $params = $this->getParam();
        $this->checkuid($params);
        $find = Clerk::where('uid',$params['uid'])->find();
        if(!$find || $find['type'] !== 2){
            $this->error('没有权限!!!!!');
        }
    }
    //店铺首页  店铺信息
    public function index(Shop $shop)
    {
        $where = array();
        $params = $this->getParam();
        $this->checkuid($params);
        $this->checkimg($params);
        !isset($params['name']) ? $this->error('参数缺失!!!!') : '';
        !isset($params['phone']) ? $this->error('参数缺失!!!!') : '';
        !isset($params['username']) ? $this->error('参数缺失!!!!') : '';
        !isset($params['address']) ? $this->error('参数缺失!!!!') : '';
        !isset($params['lng']) ? $this->error('参数缺失!!!!') : '';
        !isset($params['lat']) ? $this->error('参数缺失!!!!') : '';
        !isset($params['staff_id']) ? $this->error('参数缺失!!!!') : '';
        //$res = $this->getLatLng('河西区下瓦房琼州道43号','天津市');
        $shop->name = $params['name'];
        $shop->lng = $params['lng'];
        $shop->lat = $params['lat'];
        $shop->address = $params['address'];
        $shop->phone = $params['phone'];
        $shop->username = $params['username'];
        $shop->addtime = $this->returnDateTime();
        $shop->staff_id = $params['staff_id'];
        Db::startTrans();
        try{
            $res1 = $shop->save();
            if(!$res1){
                throw new \Exception('店铺新增失败!!!');
            }
            //自动为店铺生成一个后台管理账户
            $data['user_login'] = 'admin'.$shop->id;
            $data['user_pass'] = cmf_password('123456');
            $res2 = DB::name('user')->insertGetId($data);
            if(!$res2){
                throw new \Exception('管理员表添加失败');
            }
            $res3 = Db::name('role_user')->insert(["role_id" =>3,"user_id" => $res2]);
            if(!$res3){
                throw new \Exception('管理员角色配置失败');
            }
            $res4 = $shop->save(['admin_id'=>$res2],['id'=>$shop->id]);
            if(!$res4){
                throw new \Exception('店铺表更新失败');
            }
            Db::commit(); //提交事务
        }catch(\Exception $e){
            Db::rollback(); //回滚事务
            $this->error($e->getMessage());
        }
        $this->success('添加成功!');
    }


    private function getLatLng($address='',$city='')
    {
        $result = array();
        $ak = '7h6xR0eG4OksDz9B8jb3g2T004uBFH47';//您的百度地图ak，可以去百度开发者中心去免费申请
        $url ="http://api.map.baidu.com/geocoder/v2/?callback=renderOption&output=json&address=".$address."&city=".$city."&ak=".$ak;
        $data = file_get_contents($url);
        $data = str_replace('renderOption&&renderOption(', '', $data);
        $data = str_replace(')','', $data);
        $data = json_decode($data,true);
        if (!empty($data) && $data['status'] == 0) {
            $result['lat'] = $data['result']['location']['lat'];
            $result['lng'] = $data['result']['location']['lng'];
            return $result;//返回经纬度结果
        }else{
            return null;
        }
    }
    //店铺余额
    public function info()
    {
        $params = $this->getParam();
        $this->checkuid($params);
        $find = User::get($params['uid']);
        $info['img'] = $find['img'];
        $info['nickname'] = $find['nickname'];
        $clerk = Clerk::where('uid',$params['uid'])->find();
        $shop = Shop::get($clerk['shop_id']);
        $info['shopname'] = $shop['name'];

        $where[] = ['shop_id','eq',$clerk['shop_id']];
        $where[] = ['type','eq',1];
        $info['total'] = Balance::where($where)->SUM('balance');

        $where[] = ['addtime','like','%'.date('Y-m-d',time()).'%'];
        $info['today'] = Balance::where($where)->SUM('balance');

        $info['balance'] = $shop['balance'];
        //
        $this->success('添加成功!',$info);
    }
    //余额记录
    public function my()
    {
        $params = $this->getParam();
        $this->checkuid($params);
        $where = array();
        if(isset($params['type'])){
            $where[] = ['type','eq',$params['type']];
        }
        //$user = User::get($params['uid']);
        $shop_id = Clerk::where('uid',$params['uid'])->value('shop_id');
        $info['img'] = User::where('id',$params['uid'])->value('img');
        $where[] = ['shop_id','eq',$shop_id];
        $info['list'] = Balance::where($where)->select();
        $this->success('请求成功!',$info);
    }
    //注册店员二维码
    public function rcode()
    {
        $params = $this->getParam();
        $this->checkuid($params);
        //查询当前店员是否生成二维码
        $info = Shop::where('id',Clerk::where('uid',$params['uid'])->value('shop_id'))->find();
        if($info['rcode']){
            $this->success('请求成功!',$info['rcode']);
        }else{
            $rcode = new WxRcodeController;
            $data = json_encode(array("path"=>"pages/index/index?shop_id=".$info['id']."&type=0","width"=> 50));
            $res = $rcode->index($data,$params['uid']);
            Shop::where('id',$info['id'])->update(['rcode'=>$res]);
            $this->success('请求成功!',$res);
        }
    }
    //店铺--商品管理
    public function goodscount()
    {
        $params = $this->getParam();
        $shop_id = Clerk::where('uid',$params['uid'])->value('shop_id');
        $data['count'] = ShopGoods::where('shop_id',$shop_id)->count();
        $data['online'] = ShopGoods::where(array('shop_id'=>$shop_id,'status'=>2))->count();
        $data['unline'] = $data['count'] - $data['online'];
        $this->success('请求成功!',$data);
    }

    //店铺--商品管理--上架
    public function online()
    {
        $params = $this->getParam();
        $shop_id = Clerk::where('uid',$params['uid'])->value('shop_id');
        $goods_id = json_decode($params['goods_id'],true);
        Db::startTrans();
        try{
            foreach($goods_id as $k=>$v){
                $res[$k] = ShopGoods::where(array('shop_id'=>$shop_id,'goods_id'=>$v))->update(array('status'=>2));
                if(!$res[$k]){
                    throw new \Exception('商品id为'.$v.'商品上架失败!!!!');
                }
            }
            Db::commit();
        }catch(\Exception $e){
            Db::rollback(); //回滚事务
            $this->error($e->getMessage());
        }
        $this->success('请求成功!',true);
    }
    //店铺公告
    public function notice()
    {
        $params = $this->getParam();
        $this->checkshopid($params);
        switch($this->getMethod()){
            case 'GET':
                $list = db::name('app_shop_notice')->where('shop_id',$params['shop_id'])->select();
                $this->success('请求成功!',$list);
            break;
            case 'POST':    
                $this->checkcontent($params);
                $data['addtime'] = $this->returnDateTime();
                $data['shop_id'] = $params['shop_id'];
                $data['content'] = $params['content'];
                $res = db::name('app_shop_notice')->insert($data);
                if($res){
                    $this->success('添加成功');
                }else{
                    $this->error('添加失败');
                }
            break;
        }
    }
    //我的店员
    public function clerk()
    {
        $params = $this->getParam();
        $this->checkshopid($params);
        $list = Clerk::where('shop_id',$params['shop_id'])->all()
        ->each(function($item,$key){
            $find = User::get($item['uid']);
            $item['nickname'] = $find['nickname'];
            $item['img'] = $find['img'];
        });
        $this->success('请求成功',$list);
    }
    //修改店铺信息
    public  function shop()
    {
        $params = $this->getParam();
        $this->checkshopid($params);
        $data['id'] = $params['shop_id'];
        if(isset($params['phone'])){
            $data['phone'] = $params['phone'];
        }
        if(isset($params['username'])){
            $data['username'] = $params['username'];
        }
        if(isset($params['name'])){
            $data['name'] = $params['name'];
        }
        if(isset($params['img'])){
            $data['img'] = $params['img'];
        }
        if(isset($params['address'])){
            $data['address'] = $params['address'];
        }
        if(isset($params['lng'])){
            $data['lng'] = $params['lng'];
        }
        if(isset($params['lat'])){
            $data['lat'] = $params['lat'];
        }
        $res = Shop::update($data);
        if($res){
            $this->success('请求成功');
        }else{
            $this->error('请求失败');
        }

    }
    //我的用户
    public function user()
    {
        $params = $this->getParam();
        $this->checkshopid($params);
        $where[] = ['shop_id','eq',$params['shop_id']];
        if(isset($params['stime'])){
            $where[] = ['addtime','egt',$params['stime']];
            $where[] = ['addtime','elt',$params['etime']];
        }
        $list = User::where($where)->field('id,img,nickname,balance')->select();
        $this->success('请求成功',$list);
    }
    //订单
     //所有订单
     public function order()
     {
        $params = $this->getParam();
         $this->checkshopid($params);
         $where[] = ['shop_id','eq',$params['shop_id']];
         if(isset($params['status'])){
             if($params['status'] == 1 || $params['status'] == 2){
                 $where[] = ['status','eq',$params['status']];
             }else{
                 $where[] = ['status','eq',3];
             }
         }
         $list = Order::where($where)
             ->field('pay_price,id,is_coupon,ordernum,is_seckill,score,status,shop_id')
             ->all();
         foreach($list as $k=>$v){
             $idarr = OrderList::where('order_id',$v['id'])->all();
             $arr = array();
             foreach($idarr as $kk=>$vv){
                 $info = ShopGoods::where(['shop_id'=>$v['shop_id'],'goods_id'=>$vv['goods_id']])->find();
                 if(isset($params['status'])){
                     if($params['status'] == 3 && $info){//待收货
                         unset($idarr[$kk]);
                         continue;
                     }
                     if($params['status'] == 4 && !$info){//待自提
                         unset($idarr[$kk]);
                         continue;
                     }
                 }
                 if($info){
                     $goods['lable'] = '自提';
                 }else{
                     $goods['lable'] = '直邮';
                 }
                 $find = Goods::get($vv['goods_id']);
                 $goods['img'] = $find['img'];
                 $goods['name'] = $find['name'];
                 if($v['score']){//积分订单
                     $goods['score'] = $v['score'];
                 }
                 $goods['price'] = $vv['price'];
                 $goods['num'] = $vv['num'];
                 $arr[] = $goods;
             }
             $list[$k]['goods'] = $arr;
             if(!$list[$k]['goods']){
                 unset($list[$k]);
             }
         }
         $this->success('请求成功!',$list);
     }
     //退款审核
     public function refund()
     {
        $params = $this->getParam();

        switch($this->getMethod()){
            case 'GET':
                $this->checkshopid($params);
                $list = Refund::alias('t1')
                ->join('app_goods_order t2','t2.id = t1.order_id')
                ->where('t2.shop_id',$params['shop_id'])
                ->field('t1.*')
                ->select();
                $this->success('请求成功!',$list);
            break;
            case 'POST':
                !isset($params['refund_id']) ? $this->error('参数缺失!!!!') : '';
                !isset($params['status']) ? $this->error('参数缺失!!!!') : '';
                if($params['status'] == 3){
                    //审核拒绝 只修改状态
                    $res = Refund::where('id',$params['refund_id'])->update(array('status'=>3));
                    if($res){
                        $this->success('请求成功');
                    }else{
                        $this->error('请求失败');
                    }
                }
                if($params['status'] == 2){
                    Db::startTrans();
                    try{
                        $res = Refund::where('id',$params['refund_id'])->update(array('status'=>2));
                        if(!$res){
                            throw new \Exception('审核失败');
                        }
                        //查询当前的订单号  是那个而用户下的单
                        $info = Refund::get($params['refund_id']);
                        $order = Order::get($info['order_id']);
                        $res2 = User::where('id',$order['uid'])->setInc('balance',$info['apply_price']);
                        if(!$res2){
                            throw new \Exception('退款失败');
                        }
                        //添加  余额变动记录
                        $data['uid'] = $order['uid'];
                        $data['balance'] = $info['apply_price'];
                        $data['type'] = 1;
                        $data['remark'] = '订单退款返还余额';
                        $data['addtime'] = $this->returnDateTime();
                        $data['ordernum'] = $order['ordernum'];
                        $res3 = Balance::insert($data);
                        if(!$res3){
                            throw new \Exception('记录添加失败');
                        }
                        Db::commit(); //提交事务
                    }catch(\Exception $e){
                        Db::rollback(); //回滚事务
                        $this->error($e->getMessage());
                    }  
                }
                $this->success('退款成功!');
            break;
        }
     }
     //我的活动
    public function acvitity()
    {
        $params = $this->getParam();
        $Activity = new GoodsActivity;
        switch($this->getMethod()){
            case 'GET':
                $this->checkshopid($params);
                $Activity = new GoodsActivity;
                $list = $Activity->online($params['shop_id']);
                $this->success('请求成功!',$list);
            break;
            case 'POST':
                $this->checkshopid($params);
                $Activity->check($params) ? $this->error('参数缺失!!') : '';
                $Activity->stime = $params['stime'];
                $Activity->shop_id = $params['shop_id'];
                $Activity->etime = $params['etime'];
                $idarr = explode(',',$params['goods_id']);
                $price = explode(',',$params['goods_price']);
                foreach($idarr as $k=>$v){
                    $arr[$v] = $price[$k];
                }
                $Activity->value = json_encode($arr);
                $Activity->addtime = $this->returnDateTime();
                $res = $Activity->save();
                if($res){
                    $this->success('请求成功!');
                }else{
                    $this->error('请求失败!');
                }
            break;
        }
    }
}
